<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="前言：因为以前学习Node.js并没有真正意义上的去学习它，而是粗略的学习了npm的常用命令和Node.js一些模块化的语法，因此昨天花了一天的时间看了《Node.js开发指南》一书。通过这本书倒是让我对Node.js的认识更为全面，但由于这本书出版时间过早，有些API已经发生了变化或已经被废弃，而对于学习Node.js来说，核心部分又是最为重要的一环，因此配合官方文档对这本书的第四章-Node.">
<meta name="keywords" content="Node.js">
<meta property="og:type" content="article">
<meta property="og:title" content="Node.js核心入门（一）">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/06/Node.js核心入门（一）/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言：因为以前学习Node.js并没有真正意义上的去学习它，而是粗略的学习了npm的常用命令和Node.js一些模块化的语法，因此昨天花了一天的时间看了《Node.js开发指南》一书。通过这本书倒是让我对Node.js的认识更为全面，但由于这本书出版时间过早，有些API已经发生了变化或已经被废弃，而对于学习Node.js来说，核心部分又是最为重要的一环，因此配合官方文档对这本书的第四章-Node.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-14T09:18:50.870Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Node.js核心入门（一）">
<meta name="twitter:description" content="前言：因为以前学习Node.js并没有真正意义上的去学习它，而是粗略的学习了npm的常用命令和Node.js一些模块化的语法，因此昨天花了一天的时间看了《Node.js开发指南》一书。通过这本书倒是让我对Node.js的认识更为全面，但由于这本书出版时间过早，有些API已经发生了变化或已经被废弃，而对于学习Node.js来说，核心部分又是最为重要的一环，因此配合官方文档对这本书的第四章-Node.">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/06/Node.js核心入门（一）/"/>





  <title>Node.js核心入门（一） | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/06/Node.js核心入门（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Node.js核心入门（一）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T12:22:54+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Node-js/" itemprop="url" rel="index">
                    <span itemprop="name">Node.js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,142
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="前言："><a href="#前言：" class="headerlink" title="前言："></a>前言：</h4><p>因为以前学习Node.js并没有真正意义上的去学习它，而是粗略的学习了npm的常用命令和Node.js一些模块化的语法，因此昨天花了一天的时间看了《Node.js开发指南》一书。通过这本书倒是让我对Node.js的认识更为全面，但由于这本书出版时间过早，有些API已经发生了变化或已经被废弃，而对于学习Node.js来说，核心部分又是最为重要的一环，因此配合官方文档对这本书的第四章-Node.js核心进行了总结与梳理，如有疏漏与错误，请指正。</p>
<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><p>核心模块是Node.js的心脏，主要是有一些精简高效的库组成（这方面和Python有很大的相似之处），为Node.js提供了基础的API。主要内容包括：</p>
<p>Node.js核心入门（一）</p>
<ul>
<li>全局对象</li>
<li>常用工具</li>
<li>事件机制</li>
</ul>
<p>Node.js核心入门（二）</p>
<ul>
<li>文件系统访问</li>
<li>HTTP服务器与客户端<h2 id="全局对象"><a href="#全局对象" class="headerlink" title="全局对象"></a>全局对象</h2>全局对象我想学过JavaScript的都知道在浏览器是window，在程序的任何地方都可以访问到全局对象，而在Node.js中，这个全局对象换成了global，所有的全局变量（除了global本身）都是global对象的属性。而我们在Node.js中能够直接访问的对象通常都是global的属性，如：console，process等。<h3 id="全局对象与全局变量"><a href="#全局对象与全局变量" class="headerlink" title="全局对象与全局变量"></a>全局对象与全局变量</h3>global最根本的作用就是作为全局变量的宿主。按照ECMAScript规范，满足以下条件的变量即为全局变量：</li>
<li>在最外层定义的变量（在Node.js中不存在，因为Node.js的代码在模块中执行，不存在在最外层定义变量）</li>
<li>全局对象的属性</li>
<li>隐式定义的变量（即未定义而直接进行赋值的变量）</li>
</ul>
<p>当我们定义一个全局变量的时候，这个全局变量会自动成为全局变量的属性。</p>
<h3 id="process"><a href="#process" class="headerlink" title="process"></a>process</h3><p>process 对象是一个全局变量，它提供当前 Node.js 进程的相关信息，以及控制当前 Node.js 进程。通常我们在写本地命令行程序的时候，少不了和它打交道。下面是它的最常用的成员方法：</p>
<h4 id="1-process-argv"><a href="#1-process-argv" class="headerlink" title="1.process.argv"></a>1.process.argv</h4><p>process.argv 属性返回一个数组，这个数组包含了启动Node.js进程时的命令行参数。第一个元素为process.execPath，第二个元素为当前执行的JavaScript文件路径，剩余的元素为其他命令行参数。</p>
<p>例如存储一个名为argv.js的文件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// print process.argv</span></span><br><span class="line">process.argv.forEach(<span class="function">(<span class="params">val, index</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;index&#125;</span>: <span class="subst">$&#123;val&#125;</span>`</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>则命令行运行时这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ node process-args.js one two=three four</span><br><span class="line"></span><br><span class="line"><span class="number">0</span>: <span class="regexp">/usr/</span>local/bin/node</span><br><span class="line"><span class="number">1</span>: <span class="regexp">/Users/m</span>jr/work/node/process-args.js</span><br><span class="line"><span class="number">2</span>: one</span><br><span class="line"><span class="number">3</span>: two=three</span><br><span class="line"><span class="number">4</span>: four</span><br></pre></td></tr></table></figure>
<h4 id="2-process-stdout"><a href="#2-process-stdout" class="headerlink" title="2.process.stdout"></a>2.process.stdout</h4><p>process.stdout是标准输出流，通常我们使用的console.log()输出打印字符，而process.stdout.write()函数提供了更为底层的接口。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">process.stdout.write(<span class="string">'请输入num1的值：'</span>);</span><br></pre></td></tr></table></figure></p>
<h4 id="3-process-stdin"><a href="#3-process-stdin" class="headerlink" title="3.process.stdin"></a>3.process.stdin</h4><p>process.stdin是标准输入流，初始时它是暂停的，要想从标准输入读取数据，我们必须恢复流，并手动编写流的事件响应函数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*1:声明变量*/</span></span><br><span class="line"><span class="keyword">var</span> num1, num2;</span><br><span class="line"><span class="comment">/*2：向屏幕输出，提示信息，要求输入num1*/</span></span><br><span class="line">process.stdout.write(<span class="string">'请输入num1的值：'</span>);</span><br><span class="line"><span class="comment">/*3：监听用户的输入*/</span></span><br><span class="line">process.stdin.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">chunk</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!num1) &#123;</span><br><span class="line">        num1 = <span class="built_in">Number</span>(chunk);</span><br><span class="line">        <span class="comment">/*4：向屏幕输出，提示信息，要求输入num2*/</span></span><br><span class="line">        process.stdout.write(<span class="string">'请输入num2的值'</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        num2 = <span class="built_in">Number</span>(chunk);</span><br><span class="line">        process.stdout.write(<span class="string">'结果是：'</span> + (num1 + num2));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<h4 id="4-process-nextTick-callback-…args"><a href="#4-process-nextTick-callback-…args" class="headerlink" title="4.process.nextTick(callback[, …args])"></a>4.process.nextTick(callback[, …args])</h4><p>…args <any> 调用 callback时传递给它的额外参数<br>process.nextTick()方法将 callback 添加到”next tick 队列”。 一旦当前事件轮询队列的任务全部完成，在next tick队列中的所有callbacks会被依次调用。<br>这种方式不是setTimeout(fn, 0)的别名。它更加有效率，因此别用setTimeout去代替process.nextTick。事件轮询随后的ticks 调用，会在任何I/O事件（包括定时器）之前运行。</any></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'start'</span>);</span><br><span class="line">process.nextTick(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'nextTick callback'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'scheduled'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// start</span></span><br><span class="line"><span class="comment">// scheduled</span></span><br><span class="line"><span class="comment">// nextTick callback</span></span><br></pre></td></tr></table></figure>
<h3 id="console"><a href="#console" class="headerlink" title="console"></a>console</h3><p>console 模块提供了一个简单的调试控制台，类似于 Web 浏览器提供的 JavaScript 控制台。该模块导出了两个特定的组件：</p>
<ul>
<li>一个 Console 类，包含 console.log() 、 console.error() 和 console.warn() 等方法，可以被用于写入到任何 Node.js 流。</li>
<li>一个全局的 console 实例，可被用于写入到 process.stdout 和 process.stderr。 全局的 console 使用时无需调用 require(‘console’)。(注意：全局的 console 对象的方法既不总是同步的（如浏览器中类似的 API），也不总是异步的（如其他 Node.js 流)。</li>
</ul>
<p>比如全局下的常见的console实例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'hello，world'</span>);</span><br><span class="line"><span class="comment">// hello，world</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'hello%s'</span>, <span class="string">'world'</span>);</span><br><span class="line"><span class="comment">// helloworld</span></span><br><span class="line"><span class="built_in">console</span>.error(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'错误信息'</span>));</span><br><span class="line"><span class="comment">//  Error: 错误信息</span></span><br><span class="line"><span class="keyword">const</span> name = <span class="string">'描述'</span>;</span><br><span class="line"><span class="built_in">console</span>.warn(<span class="string">`警告<span class="subst">$&#123;name&#125;</span>`</span>);</span><br><span class="line"><span class="comment">// 警告描述</span></span><br><span class="line"><span class="built_in">console</span>.trace() <span class="comment">// 向标准错误流输出当前的调用栈</span></span><br><span class="line"><span class="string">``</span><span class="string">`JavaScript</span></span><br><span class="line"><span class="string">常见的Console类：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>JavaScript</span><br><span class="line"><span class="keyword">const</span> out = getStreamSomehow();</span><br><span class="line"><span class="keyword">const</span> err = getStreamSomehow();</span><br><span class="line"><span class="keyword">const</span> myConsole = <span class="keyword">new</span> <span class="built_in">console</span>.Console(out, err);</span><br><span class="line"></span><br><span class="line">myConsole.log(<span class="string">'hello，world'</span>);</span><br><span class="line"><span class="comment">// hello，world</span></span><br><span class="line">myConsole.log(<span class="string">'hello%s'</span>, <span class="string">'world'</span>);</span><br><span class="line"><span class="comment">// helloworld</span></span><br><span class="line">myConsole.error(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'错误信息'</span>));</span><br><span class="line"><span class="comment">// Error: 错误信息</span></span><br><span class="line"><span class="keyword">const</span> name = <span class="string">'描述'</span>;</span><br><span class="line">myConsole.warn(<span class="string">`警告<span class="subst">$&#123;name&#125;</span>`</span>);</span><br><span class="line"><span class="comment">//警告描述</span></span><br></pre></td></tr></table></figure>
<h2 id="常用工具-util"><a href="#常用工具-util" class="headerlink" title="常用工具  util"></a>常用工具  util</h2><p>util 模块主要用于支持 Node.js 内部 API 的需求。 大部分实用工具也可用于应用程序与模块开发者，用于弥补核心JavaScript的功能的不足。它的可以这样调用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> util = <span class="built_in">require</span>(<span class="string">'util'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="1-util-inspect-object-options"><a href="#1-util-inspect-object-options" class="headerlink" title="1.util.inspect(object[, options])"></a>1.util.inspect(object[, options])</h3><p>util.inspect() 方法返回 object 的字符串表示，主要用于调试和错误输出。 附加的 options 可用于改变格式化字符串的某些方面。它至少接受一个参数objet，即要转换的参数，而option则是可选的，可选内容如下：</p>
<ul>
<li>showHidden <boolean> 如果为 true，则 object 的不可枚举的符号与属性也会被包括在格式化后的结果中。 默认为 false。</boolean></li>
<li>depth <number> 指定格式化 object 时递归的次数。 这对查看大型复杂对象很有用。 默认为 2。 若要无限地递归则传入 null。</number></li>
<li>colors <boolean> 如果为 true，则输出样式使用 ANSI 颜色代码。 默认为 false，可自定义。</boolean></li>
<li>customInspect <boolean> 如果为 false，则 object 上自定义的 inspect(depth, opts) 函数不会被调用。 默认为 true。</boolean></li>
<li>showProxy <boolean> 如果为 true，则 Proxy 对象的对象和函数会展示它们的 target 和 handler 对象。 默认为 false。</boolean></li>
<li>maxArrayLength <number> 指定格式化时数组和 TypedArray 元素能包含的最大数量。 默认为 100。 设为 null 则显式全部数组元素。 设为 0 或负数则不显式数组元素。</number></li>
<li>breakLength <number> 一个对象的键被拆分成多行的长度。 设为 Infinity 则格式化一个对象为单行。 默认为 60。</number></li>
</ul>
<p>例如，查看 util 对象的所有属性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> util = <span class="built_in">require</span>(<span class="string">'util'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(util.inspect(util, &#123; <span class="attr">showHidden</span>: <span class="literal">true</span>, <span class="attr">depth</span>: <span class="literal">null</span> &#125;));</span><br></pre></td></tr></table></figure>
<h3 id="2-util-callbackify-original"><a href="#2-util-callbackify-original" class="headerlink" title="2.util.callbackify(original)"></a>2.util.callbackify(original)</h3><p>util.callbackify(original)方法将 async 异步函数(或者一个返回值为 Promise 的函数)转换成遵循 Node.js 回调风格的函数。 在回调函数中, 第一个参数 err 为 Promise rejected 的原因 (如果 Promise 状态为 resolved , err为 null ),第二个参数则是 Promise 状态为 resolved 时的返回值。例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> util = <span class="built_in">require</span>(<span class="string">'util'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">await</span> <span class="built_in">Promise</span>.resolve(<span class="string">'hello world'</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> callbackFunction = util.callbackify(fn);</span><br><span class="line"></span><br><span class="line">callbackFunction(<span class="function">(<span class="params">err, ret</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="built_in">console</span>.log(ret);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// hello world</span></span><br></pre></td></tr></table></figure>
<p>注意：</p>
<ul>
<li>回调函数是异步执行的, 并且有异常堆栈错误追踪. 如果回调函数抛出一个异常, 进程会触发一个 ‘uncaughtException’ 异常, 如果没有被捕获, 进程将会退出。</li>
<li>null 在回调函数中作为一个参数有其特殊的意义, 如果回调函数的首个参数为 Promise rejected 的原因且带有返回值, 且值可以转换成布尔值 false, 这个值会被封装在 Error 对象里, 可以通过属性 reason 获取。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.reject(<span class="literal">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> callbackFunction = util.callbackify(fn);</span><br><span class="line"></span><br><span class="line">callbackFunction(<span class="function">(<span class="params">err, ret</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 当Promise的rejecte是null时，它的Error与原始值都会被存储在'reason'中。</span></span><br><span class="line">  err &amp;&amp; err.hasOwnProperty(<span class="string">'reason'</span>) &amp;&amp; err.reason === <span class="literal">null</span>;  <span class="comment">// true</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="事件驱动-events"><a href="#事件驱动-events" class="headerlink" title="事件驱动  events"></a>事件驱动  events</h2><p>events是Node.js最重要的模块，原因是Node.js本身架构就是事件式的，大多数 Node.js 核心 API 都采用惯用的异步事件驱动架构，而它提供了唯一的接口，因此堪称Node.js事件编程的及时。events 模块不仅用于用户代码与 Node.js 下层事件循环的交互，还几乎被所有的模块依赖。</p>
<p>所有能触发事件的对象都是 EventEmitter 类的实例。 这些对象开放了一个 eventEmitter.on() 函数，允许将一个或多个函数绑定到会被对象触发的命名事件上。 事件名称通常是驼峰式的字符串，但也可以使用任何有效的 JavaScript 属性名。对于每个事件， EventEmitter支持<br>若干个事件监听器。当事件发射时，注册到这个事件的事件监听器被依次调用，事件参数作<br>为回调函数参数传递。</p>
<p>例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">'events'</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyEmitter</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> myEmitter = <span class="keyword">new</span> MyEmitter();</span><br><span class="line"><span class="comment">// eventEmitter.on() 方法用于注册监听器</span></span><br><span class="line">myEmitter.on(<span class="string">'event'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'触发了一个事件！'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// eventEmitter.emit() 方法用于触发事件</span></span><br><span class="line">myEmitter.emit(<span class="string">'event'</span>);</span><br></pre></td></tr></table></figure>
<p>下面让我们来看看EventEmitter最常用的API：</p>
<ul>
<li>EventEmitter.on(event, listener) 方法可以添加 listener 函数到名为 eventName 的事件的监听器数组的末尾。不会检查 listener 是否已被添加。多次调用并传入相同的 eventName 和 listener 会导致 listener 被添加与调用多次。</li>
<li>emitter.prependListener(eventName, listener)方法可以添加 listener 函数到名为 eventName 的事件的监听器数组的开头。 不会检查 listener 是否已被添加。 多次调用并传入相同的 eventName 和 listener 会导致 listener 被添加与调用多次。</li>
<li><p>eventEmitter.emit() 方法允许将任意参数传给监听器函数。当一个普通的监听器函数被 EventEmitter 调用时，标准的 this 关键词会被设置指向监听器所附加的 EventEmitter。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 实例：</span></span><br><span class="line"><span class="keyword">const</span> myEE = <span class="keyword">new</span> EventEmitter();</span><br><span class="line">myEE.on(<span class="string">'foo'</span>, () =&gt; <span class="built_in">console</span>.log(<span class="string">'a'</span>));</span><br><span class="line">myEE.prependListener(<span class="string">'foo'</span>, () =&gt; <span class="built_in">console</span>.log(<span class="string">'b'</span>));</span><br><span class="line">myEE.emit(<span class="string">'foo'</span>);</span><br><span class="line"><span class="comment">// 打印:</span></span><br><span class="line"><span class="comment">//   b</span></span><br><span class="line"><span class="comment">//   a</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>EventEmitter.once(event, listener)  为指定事件注册一个单次监听器，即监听器最多只会触发一次，触发后立刻解除该监听器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">server.once(<span class="string">'connection'</span>, (stream) =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'首次调用！'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>EventEmitter.removeListener(event, listener) 移除指定事件的某个监听器， listener 必须是该事件已经注册过的监听器。（注意：removeListener 最多只会从监听器数组里移除一个监听器实例。 如果任何单一的监听器被多次添加到指定 eventName 的监听器数组中，则必须多次调用 removeListener 才能移除每个实例。）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">const callback = (stream) =&gt; &#123;</span><br><span class="line">  console.log(&apos;有连接！&apos;);</span><br><span class="line">&#125;;</span><br><span class="line">server.on(&apos;connection&apos;, callback);</span><br><span class="line">// ...</span><br><span class="line">server.removeListener(&apos;connection&apos;, callback);</span><br></pre></td></tr></table></figure>
</li>
<li><p>EventEmitter.removeAllListeners([event]) 移除所有事件的所有监听器，如果指定  event ，则移除指定事件的所有监听器</p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> callback = <span class="function">(<span class="params">stream</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'有连接！'</span>);</span><br><span class="line">&#125;;</span><br><span class="line">server.on(<span class="string">'connection'</span>, callback);</span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">server.removeListener(<span class="string">'connection'</span>, callback);</span><br></pre></td></tr></table></figure>
<h3 id="error-事件"><a href="#error-事件" class="headerlink" title="error 事件"></a>error 事件</h3><p>EventEmitter 定义了一个特殊的事件  error ，它包含了“错误”的语义，我们在遇到异常的时候通常会发射 error 事件。当 error被发射时，EventEmitter规定如果没有响<br>应的监听器，Node.js 会把它当作异常，退出程序并打印调用栈。我们一般要为会发射 error 事件的对象设置监听器，避免遇到错误后整个程序崩溃。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> events = <span class="built_in">require</span>(<span class="string">'events'</span>);</span><br><span class="line"><span class="keyword">var</span> emitter = <span class="keyword">new</span> events.EventEmitter();</span><br><span class="line">emitter.emit(<span class="string">'error'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="继承EventEmitter"><a href="#继承EventEmitter" class="headerlink" title="继承EventEmitter"></a>继承EventEmitter</h3><p>大多数情况下，我们不会直接使用EventEmitter，而是在对象中继承它，包括fs,http在内的只要是支持事件响应的核心模块都是EventEmitter的子类。这样做的原因有以下两个：</p>
<ul>
<li>具有某个实体功能的对象实现事件符合语义，事件的监听和发射应该是一个对象的方法。</li>
<li>JavaScript 的对象机制是基于原型的，支持<br>部分多重继承，继承  EventEmitter 不会打乱对象原有的继承关系。</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/Node.js核心入门（二）/" rel="next" title="Node.js核心入门（二）">
                <i class="fa fa-chevron-left"></i> Node.js核心入门（二）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/06/3.组件数据/" rel="prev" title="3.组件数据">
                3.组件数据 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#前言："><span class="nav-number">1.</span> <span class="nav-text">前言：</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#正文"><span class="nav-number"></span> <span class="nav-text">正文</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#全局对象"><span class="nav-number"></span> <span class="nav-text">全局对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#全局对象与全局变量"><span class="nav-number"></span> <span class="nav-text">全局对象与全局变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#process"><span class="nav-number"></span> <span class="nav-text">process</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-process-argv"><span class="nav-number">1.</span> <span class="nav-text">1.process.argv</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-process-stdout"><span class="nav-number">2.</span> <span class="nav-text">2.process.stdout</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-process-stdin"><span class="nav-number">3.</span> <span class="nav-text">3.process.stdin</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-process-nextTick-callback-…args"><span class="nav-number">4.</span> <span class="nav-text">4.process.nextTick(callback[, …args])</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#console"><span class="nav-number"></span> <span class="nav-text">console</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用工具-util"><span class="nav-number"></span> <span class="nav-text">常用工具  util</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-util-inspect-object-options"><span class="nav-number"></span> <span class="nav-text">1.util.inspect(object[, options])</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-util-callbackify-original"><span class="nav-number"></span> <span class="nav-text">2.util.callbackify(original)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事件驱动-events"><span class="nav-number"></span> <span class="nav-text">事件驱动  events</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#error-事件"><span class="nav-number"></span> <span class="nav-text">error 事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#继承EventEmitter"><span class="nav-number"></span> <span class="nav-text">继承EventEmitter</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
